<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head th:include="include :: header"></head>
<body class="hold-transition skin-blue sidebar-mini">
<section class="content-header">
    <h1>机加工时确认单变更</h1>
</section>
<!--导入模态框-->
<div class="modal fade" data-backdrop="static" data-keyboard="false" id="modal-import-plan">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">Excel信息导入</h4>
            </div>
            <div class="modal-body">
                <form id="importForm">
                    <div class="form-group">
                        <label>模版</label>
                        <a class="out" th:href="@{/file/机加工时计划单录入模板.xlsx}">点击下载</a>
                    </div>
                    <div class="form-group">
                        <label>选择Excel文件并上传</label>
                        <input id="import-file" class="btn" type="file" name="file">
                        <p class="help-block">请按模板格式进行导入，信息与模板信息对应。</p>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button id="btn-import" type="button" class="btn btn-success">
                    <span class="Bold">确定</span>
                </button>
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
            </div>
        </div>
    </div>
</div>
<!--上传附件-->
<div class="modal fade" data-backdrop="static" data-keyboard="false" id="modal-upload">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">上传附件</h4>
            </div>
            <div class="modal-body">
                <form id="uploadForm">
                    <div class="form-group">
                        <label>选择附件上传</label>
                        <input class="btn" type="file" name="file">
                        <p class="help-block">多个文件请自行打包上传，大小不要超过100M</p>
                        <p class="help-block text-red">多条计划附件不支持上传同名文件</p>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button shiro:hasPermission="production:make:edit" id="btn-upload" type="button"
                        class="btn btn-success">
                    <span class="Bold">上传</span>
                </button>
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
            </div>
        </div>
    </div>
</div>
<section class="content">
    <div class="row" style="margin-bottom: 24px">
        <a id="btn-save" shiro:hasPermission="cost:machiningPlan:edit" href="javascript:void(0);"
           class="btn btn-info pull-right" style="margin-right: 10px">
            <span class="Bold">确定</span>
        </a>
        <a shiro:hasPermission="cost:machiningPlan:edit" href="javascript:void(0);"
           class="btn btn-success pull-right" style="margin-right: 10px"
           onclick="js.modal.open('modal-import-plan')">
            <span class="Bold">导入</span>
        </a>
    </div>
    <div class="row">
        <form id="sheetForm" class="form-horizontal">
            <div class="col-xs-11 col-xs-offset-1">
                <input type="hidden" name="reportType" value="1">
                <table class="t1 t3">
                    <thead>
                    <tr>
                        <td colspan="13">
                            <img th:src="@{/img/logo3.jpg}" width="64px" height="40px" style="margin-top: -30px">
                            <div style="display: inline-block;margin-top: 5px;margin-left: 20px">
                                <span style="letter-spacing: 24px;display: block;line-height: 20px">&nbsp;辽宁忠旺机械设备制造有限公司</span>
                                <span style="display: block;font-size: 12px;line-height: 20px">Liaoning Zhongwang Machinery Equipment Manufacturing Co., Ltd</span>
                            </div>
                        </td>
                        <td style="width: 8%"></td>
                    </tr>
                    <tr>
                        <td colspan="13" style="font-size: 16px;letter-spacing: 4px;">
                            机加工时计划单
                        </td>
                        <td></td>
                    </tr>
                    <tr>
                        <td colspan="2" style="width: 8%">项目编号</td>
                        <td style="width: 11%;font-size: 14px;">
                            <input type="hidden" name="id" th:value="${cosSheet.id}">
                            <input type="hidden" name="proId" th:value="${cosSheet.proId}">
                            <input id="sheetForm-proCode" class="form-control" name="proCode" th:value="${cosSheet.proCode}" readonly></input>
                        </td>
                        <td style="width: 8%">项目名称</td>
                        <td colspan="3" style="width: 21%">
                            <input id="sheetForm-proName" type="text" class="form-control" name="proName" th:value="${cosSheet.proName}" readonly>
                        </td>
                        <td style="width: 8%">项目数量</td>
                        <td style="width: 6%">
                            <input id="sheetForm-proNum" type="number" class="form-control" name="proNum" th:value="${cosSheet.proNum}" readonly>
                        </td>
                        <td style="width: 6%">类型</td>
                        <td style="width: 9%">
                            <select id="sheetForm-malType" class="form-control" name="special">
                                <option value="">请选择</option>
                                <option value="机械" th:selected="${cosSheet.special == '机械'}">机械</option>
                                <option value="流体" th:selected="${cosSheet.special == '流体'}">流体</option>
                                <option value="自动化" th:selected="${cosSheet.special == '自动化'}">自动化</option>
                            </select>
                        </td>
                        <td style="width: 6%">部分</td>
                        <td style="width: 12%">
                            <!--<select id="part" class="form-control" name="proPartId">-->
                                <!--<option value="" selected>请选择</option>-->
                                <!--<option th:each="p : ${proPart}" th:value="${p.id}"-->
                                        <!--th:text="|${p.special}-${p.proPart}|" th:selected="${p.proPart == cosSheet.proPart}"></option>-->
                            <!--</select>-->
                            <select id="part" class="form-control" name="proPartId"
                                    style="border: none; border-bottom: solid 1px #EEEEEE;width:150px;-webkit-appearance:none;">
                                <option value="" selected>请选择</option>
                                <option th:each="p : ${proPart}" th:value="${p.id}"
                                        th:text="|${p.special}-${p.proPart}|" th:selected="${p.proPart == cosSheet.proPart}"></option>
                            </select>
                        </td>
                        <td>
                        </td>
                    </tr>
                    <tr>
                        <td style="width: 4%">序号</td>
                        <td colspan="2">图号</td>
                        <td colspan="3">图名</td>
                        <td style="width: 6%">数量</td>
                        <td colspan="1">工序</td>
                        <td colspan="2">设备</td>
                        <td colspan="1">工时</td>
                        <td colspan="2">备注</td>
                        <td></td>
                    </tr>
                    </thead>
                    <tbody id="out">
                    <tr  th:each="cosMachiningDetail:${cosMachiningDetail}">
                        <td th:text="${cosMachiningDetailStat.count}">1</td>
                        <td colspan="2">
                            <input style="text-align:left;" type="text" class="form-control" name="drawNo" autocomplete="off" th:value="${cosMachiningDetail.drawNo}" >
                        </td>
                        <td colspan="3">
                            <input type="text" class="form-control" name="drawName" autocomplete="off" th:value="${cosMachiningDetail.drawName}" >
                        </td>
                        <td colspan="1">
                            <input type="number" class="form-control" name="drawNum" autocomplete="off" th:value="${cosMachiningDetail.drawNum}" >
                        </td>
                        <td colspan="1">
                            <select class="form-control" name="process" title="">
                                <option value=""></option>
                                <option th:each="p : ${processes}" th:value="${p.name}"
                                        th:text="${p.name}" th:selected="${p.name == cosMachiningDetail.process}"></option>
                            </select>
                        </td>
                        <td colspan="2">
                            <select class="form-control" name="equName" title="">
                                <option value=""></option>
                                <option th:each="e : ${equNames}" th:value="${e.name}"
                                        th:text="${e.name}" th:selected="${e.name == cosMachiningDetail.equName}"></option>
                            </select>
                        </td>
                        <td colspan="1">
                            <input type="number" step="0.1"   class="form-control" name="quantity" autocomplete="off"  th:value="${cosMachiningDetail.quantity}">
                        </td>
                        <td colspan="2">
                            <input type="text" class="form-control" name="remark" autocomplete="off" th:value="${cosMachiningDetail.remark}" >
                        </td>
                        <td>
                            <span class="out-add" title="添加"><i class="fa fa-plus text-info"></i> </span>
                            <span class="out-del" title="删除"><i class="fa fa-remove text-red"></i> </span>
<!--                            <span class="out-upload" title="上传附件"><i class="fa fa-upload text-success"></i> </span>-->
                        </td>
                    </tr>
                    </tbody>
                </table>
            </div>
            <div class="col-xs-10 col-xs-offset-1" style="font-size: 14px;line-height: 200%;">
                <div class="col-xs-3" style="padding-left: 0">提报人： [[${session.user.name}]]</div>
                <!--<div class="col-xs-3 bottom form-inline">联系电话：-->
                    <!--<input class="form-control" style="width:60%;border: none;border-bottom: 1px solid #000;" type="text" name="postTel">-->
                <!--</div>-->
            </div>
        </form>
    </div>
<!--
    <div th:include="include :: tip"></div>
-->
</section>
<div th:include="include :: footer"></div>

<div id="div-process" style="display: none">
    <select class="form-control" name="process" title="">
        <option value=""></option>
        <option th:each="p : ${processes}" th:value="${p.name}"
                th:text="${p.name}"></option>
    </select>
</div>
<div id="div-equName" style="display: none">
    <select class="form-control" name="equName" title="">
        <option value=""></option>
        <option th:each="e : ${equNames}" th:value="${e.name}"
                th:text="${e.name}"></option>
    </select>
</div>
<script th:src="@{/plugin/SheetJs/xlsx.core.min.js}"></script>
<script th:inline="javascript">
    let tempUrl;

    /** 计算表格序号 */
    function computerNo() {
        $("table tbody tr").each(function (i, e) {
            $(this).children("td:first").text(i + 1);
        });
    }

    /** orderNum的计算序号*/
    function orderNumber(){
        var obj = document.getElementsByName("orderNum");
        for (var i = 0; i < obj.length; i++) {
            obj[i].value = i+1;
        }
    }

    function getPartName(){
        let code = $("#sheetForm-proCode").val();
        let type = $("#sheetForm-malType").val();
        /** 部分的级联获取*/
        js.get({
            url: ctx + 'production/add/part/list',
            data: {
                code :code,
                type: type
            },
            success: function (result) {
                $("#part").empty().append(`<option value="">请选择</option>`);
                result.forEach(value => {
                    if (value) {
                        $("#part").append(`<option value="${value.id}">${value.proPart}</option>`);
                    }
                })
            }
        })
    }
    //正则表达式 判断时间工时 小数位最大到0.6
    function checkNum(obj) {
        console.log(obj);
        var re = /^[0-9]+(.[0-5][0-9]{0,1})?$/;
        console.log(obj.value);
        if (!re.test(obj.value)) {
            obj.value = "";

        }
    }

    /** 获取部分 */
    function getPart() {
        let code = $("#sheetForm-proCode").val();
        let type = $("#sheetForm-malType").val();
        switch (type) {
            case '机械' :
            case '流体' :
            case '自动化' :
                fetchPart(code, type);
                break;
            case '外观' :
                fetchPart(code, null);
                break;
        }
    }
    function fetchPart(code, type) {
        js.get({
            url: ctx + 'tecout/tecnote/part/list',
            data: {
                code : code,
                type : type
            },
            success: function (result) {
                $("#part").empty().append(`<option value="">请选择</option>`);
                result.forEach(value => {
                    if (value) {
                        $("#part").append(`<option value="${value.id}">${value.special}-${value.proPart}</option>`);
                    }
                })
            }
        })
    }
    $(function () {

        let makeTypeHtml = $("#div-makeType").html();
        let processHtml = $("#div-process").html();
        let equNameHtml = $("#div-equName").html();
        orderNumber();


        $("#sheetForm-malType").change(function (){
            /** 部分的级联获取*/
            getPart();

        })


        /** 添加一行 */
        $("#sheetForm").on('click', '.out-add', function () {
            $(this).parents("tr").after(`
                    <tr>
                        <td name="orderNum"></td>
                       <td colspan="2">
                            <input style="text-align:left;" type="text" class="form-control" name="drawNo" autocomplete="off">
                        </td>
                        <td colspan="3">
                            <input type="text" class="form-control" name="drawName" autocomplete="off">
                        </td>
                        <td>
                            <input type="number"  class="form-control" name="drawNum" autocomplete="off">
                        </td>
                        <td colspan="1">
                            ${processHtml}
                        </td>
                         <td colspan="2">
                            ${equNameHtml}
                        </td>
                         <td colspan="1">
                            <input type="number" onblur="checkNum(this)" step="0.1" class="form-control" name="quantity" autocomplete="off">
                        </td>
                        <td colspan="2">
                            <input type="text"  class="form-control" name="remark" autocomplete="off">
                        </td>
                        <td>
                            <span class="out-add" title="添加"><i class="fa fa-plus text-info"></i> </span>
                            <span class="out-del" title="删除"><i class="fa fa-remove text-red"></i> </span>
<!--                            <span class="out-upload" title="上传附件"><i class="fa fa-upload text-success"></i> </span>-->
                        </td>
                    </tr>
            `);
            computerNo();
            orderNumber()
        });

        /** 导入 */
        $('#btn-import').click(function() {

            let files = $("#import-file")[0].files;
            // let files = e.target.files;
            let fileReader = new FileReader();
            fileReader.onload = function(ev) {
                try {
                    let data = ev.target.result,
                        workbook = XLSX.read(data, {type: 'binary'}), // 以二进制流方式读取得到整份excel表格对象
                        plans = []; // 存储获取到的数据
                    // 遍历每张表读取
                    for (let sheet in workbook.Sheets) {
                        if (workbook.Sheets.hasOwnProperty(sheet)) {
                            plans = plans.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
                            break; // 只取第一张表
                        }
                    }
                    if (plans.length === 0) {
                        js.modal.alert("无法读取文件内容");
                    } else {
                        $("#out").empty();
                        plans.forEach((value, index) => {
                            let r = value['备注'] || '';
                            $("#out").append(`
                                <tr>
                                    <td></td>
                                    <td colspan="2">
                                        <input style="text-align:left;" type="text" class="form-control" name="drawNo" value="${value['图号']}" autocomplete="off">
                                    </td>
                                    <td colspan="3">
                                        <input type="text" class="form-control" name="drawName" value="${value['图名']}"  autocomplete="off">
                                    </td>
                                    <td>
                                        <input type="number" step="0.1" class="form-control" name="drawNum" value="${value['数量']}" autocomplete="off">
                                    </td>
                                    <td colspan="1">
                                       ${processHtml}
                                    </td>
                                     <td colspan="2">
                                       ${equNameHtml}
                                    </td>
                                     <td colspan="1">
                                         <input type="number" step="0.1"  class="form-control" name="quantity" value="${value['工时']}" autocomplete="off">
                                    </td>
                                    <td colspan="2">
                                        <input type="text" class="form-control" name="remark" value="${r}"  autocomplete="off">
                                    </td>
                                    <td>
                                        <span class="out-add" title="添加"><i class="fa fa-plus text-info"></i> </span>
                                        <span class="out-del" title="删除"><i class="fa fa-remove text-red"></i> </span>
<!--                                        <span class="out-upload" title="上传附件"><i class="fa fa-upload text-success"></i> </span>-->
                                    </td>
                                </tr>

                            `);
                            $("#out").find("select[name=process]:last").val(value['工序'])
                            $("#out").find("select[name=equName]:last").val(value['设备'])
                        });
                        computerNo();
                        orderNumber()
                        js.modal.hide("modal-import-plan");
                    }
                } catch (e) {
                    js.modal.alert("无法读取文件或文件类型有错误");
                }
            };
            // 以二进制方式打开文件
            fileReader.readAsBinaryString(files[0]);
        });

        /** 删除行 */
        $('#sheetForm').on('click', '.out-del', function () {
            $(this).parents("tr").remove();
            if ($("table tbody tr").length === 0) {
                $("#out").append(`
                                <tr>
                                    <td></td>

                                    <td colspan="2">
                                        <input style="text-align:left;" type="text" class="form-control" name="drawNo" autocomplete="off">
                                    </td>
                                    <td colspan="3">
                                        <input type="text" class="form-control" name="drawName" autocomplete="off">
                                    </td>
                                    <td>
                                        <input type="number" class="form-control" name="drawNum" autocomplete="off">
                                    </td>
                                    <td colspan="1">
                                       ${processHtml}
                                    </td>
                                    <td colspan="2">
                                       ${equNameHtml}
                                    </td>
                                       <td colspan="1">
                                        <input type="number" step="0.1"  onblur="checkNum(this)" class="form-control" name="quantity" autocomplete="off">
                                    </td>
                                    <td colspan="2">
                                        <input type="text" class="form-control" name="remark" autocomplete="off">
                                    </td>
                                    <td>
                                        <span class="out-add" title="添加"><i class="fa fa-plus text-info"></i> </span>
                                        <span class="out-del" title="删除"><i class="fa fa-remove text-red"></i> </span>
<!--                                        <span class="out-upload" title="上传附件"><i class="fa fa-upload text-success"></i> </span>-->
                                    </td>
                                </tr>
                            `)
            }
            computerNo();
            orderNumber()
        });

        $("#sheetForm").on('click', '.out-upload', function () {
            tempUrl = $(this).parents("tr").find("input[name=url]");
            js.modal.open('modal-upload');
        });
        /** 初始化验证 */
        js.validate.init("uploadForm", {
            fields: {
                file: {
                    validators: {
                        notEmpty: {message: '上传文件不能为空'}
                    }
                }
            }
        });
        /** 上传附件 */
        $("#btn-upload").click(function () {
           ;
            var $this = $(this);
            $this.attr('disabled', true);
            js.validSubmit({
                formId: "uploadForm",
                url: ctx + "production/add/upload",
                data: new FormData($("#uploadForm")[0]),
                success: function (result) {
                    if (result.type === web_status.SUCCESS) {
                        js.modal.alert(result.msg);
                        tempUrl.val(result.data);
                        js.modal.hide("modal-upload");
                    } else {
                        js.modal.warning(result.msg);
                    }
                }
            });
            $this.attr('disabled', false);
        });
        /** 重置表单及验证 */
        js.modal.hideEvent("modal-upload", function () {
            js.validate.reset("uploadForm");
            js.reset("uploadForm");
        })

        /** 保存计划单 */
        $("#btn-save").click(function () {
            let $this = $(this);
            $("#specialse").val($("#sheetForm-malType option:selected").text());
            $("#partName").val($("#part option:selected").text());
            let isT=panduangongshi({
                id: 'sheetForm',
                notEmpty: ['quantity']
            });
            if(!isT){
                return;
            }
            let res = js.vd({
                id: 'sheetForm',
                notEmpty: ['proCode','proPartId','specialId', 'drawNo', 'drawNum', 'drawName','process', 'equName','quantity']
            })
            if (!res) {
                return;
            }
            $this.attr('disabled', true);
            js.submit({
                formId: "sheetForm",
                url: ctx + 'craft/cost/machining/saveUpdate',
                data: new FormData($("#sheetForm")[0]),
                success: function (result) {
                   ;
                    if (result.type === web_status.SUCCESS) {
                        if(result.data===-2){
                            alert(result.msg);
                            return;
                        }else if(result.data===-1) {
                            js.modal.success(result.msg);
                        }else {
                            location.href = ctx + "craft/cost/machining/submit";

                        }
                    } else {
                        js.modal.warning(result.msg);
                    }
                }
            });
            $this.removeAttr('disabled');
        });

    });
    function panduangongshi(option){
        let defaults = {
            id: "form",
        };
        let opt = $.extend(defaults, option);
        let that = $("#" + opt.id);
        if (opt.notEmpty instanceof Array) {
            opt.notEmpty.forEach(value => {
                let target = that.find(`[name=${value}]`);
                target.each(function (i,v) {
                    if ($(this).val()%1 >= 0.6) {
                        $(this).addClass('vd-error');
                        $(this).css('border', '1px solid #FF3333');
                    } else {
                        $(this).removeClass('vd-error');
                        $(this).css('border', 'none');
                    }
                })
            })
        }
        return that.find(".vd-error").length === 0
    }
</script>
</body>
</html>
